package com.ruoyi.im.service;

import com.ruoyi.im.entity.MsgRoute;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 离线消息服务
 */
@Service
public class OffLineMsgService {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    private final String OFFLINE_MSG_KEY_PREFIX = "ws:session:offline:";

    @Autowired
    private MsgService msgService;


    /**
     * 添加一个新的离线消息
     * 这里注意，因为是mq投递，所以这里的消息并不一定是有序的。
     *
     * @param msgRoute
     */
    public void addNewOfflineMsg(MsgRoute msgRoute) {
        Integer receiverId = msgRoute.getReceiverId();
        //保存消息到数据库中
        ListOperations<String, Object> lop = redisTemplate.opsForList();
        lop.rightPush(OFFLINE_MSG_KEY_PREFIX + receiverId, msgRoute);
    }

    public List<Object> getOfflineMsg(Integer userId) {
        ListOperations<String, Object> lop = redisTemplate.opsForList();
        String key = OFFLINE_MSG_KEY_PREFIX + userId;
        Long size = lop.size(key);
        if (size == 0) {
            return null;
        }
        List<Object> rst = lop.range(key, 0, -1);
        //清空
        redisTemplate.delete(key);
        return rst;
    }
}
